package com.lzb.randomturntable.adapter;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import androidx.annotation.NonNull;

import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.lzb.basic.ProviderMultiAdapter;
import com.lzb.randomturntable.R;

public class OptionAdapter extends ProviderMultiAdapter<String> {

    private OnOptionChangeListener onOptionChangeListener;

    public OptionAdapter() {
        addItemProvider(new OptionProvider());
    }

    public void setOnOptionChangeListener(OnOptionChangeListener listener) {
        this.onOptionChangeListener = listener;
    }

    public interface OnOptionChangeListener {
        void onOptionChanged(int position, String newText);
    }

    private class OptionProvider extends BaseItemProvider<String> {
        @Override
        public int getItemViewType() {
            return ProviderMultiAdapter.TYPE_VIEW;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_option;
        }

        @Override
        public void convert(@NonNull BaseViewHolder baseViewHolder, String bean) {
            EditText editText = baseViewHolder.getView(R.id.etOptionItemName);
            editText.setText(bean);
            
            // 移除之前的TextWatcher避免重复
            Object existingWatcher = editText.getTag();
            if (existingWatcher instanceof TextWatcher) {
                editText.removeTextChangedListener((TextWatcher) existingWatcher);
            }
            
            // 创建新的TextWatcher
            TextWatcher textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    int position = baseViewHolder.getAdapterPosition();
                    if (position != -1 && onOptionChangeListener != null) {
                        onOptionChangeListener.onOptionChanged(position, s.toString());
                    }
                }
            };
            
            // 存储TextWatcher引用到tag中
            editText.setTag(textWatcher);
            editText.addTextChangedListener(textWatcher);
        }
    }
}